<template>
  <div class="customer-select">
    <el-form label-width="120px">

      <!-- 客户标签选择 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="客户标签">
            <el-select 
              v-model="selectedTags" 
              multiple 
              placeholder="请选择客户标签"
              style="width: 100%">
              <el-option
                v-for="tag in customerTags"
                :key="tag.value"
                :label="tag.label"
                :value="tag.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 客户分层选择 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="客户分层">
            <el-select 
              v-model="selectedSegments" 
              multiple 
              placeholder="请选择客户分层"
              style="width: 100%">
              <el-option
                v-for="segment in customerSegments"
                :key="segment.id"
                :label="segment.segmentName"
                :value="segment.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 时间条件选择 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="时间条件">
            <el-radio-group v-model="timeRangeOption" @change="handleTimeRangeChange">
              <el-radio-button label="3d">近3天</el-radio-button>
              <el-radio-button label="7d">近7天</el-radio-button>
              <el-radio-button label="1m">近1个月</el-radio-button>
              <el-radio-button label="custom">自定义</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 自定义时间范围选择器 -->
      <el-row v-if="timeRangeOption === 'custom'">
        <el-col :span="24">
          <el-form-item label="自定义时间">
            <el-date-picker
              v-model="customTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 开始时间和结束时间只读输入框 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间">
            <el-input 
              v-model="form.startTime" 
              readonly 
              placeholder="开始时间">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间">
            <el-input 
              v-model="form.endTime" 
              readonly 
              placeholder="结束时间">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 客户选择树 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择客户">
            <el-tree
              ref="customerTreeRef"
              :data="customerTreeData"
              show-checkbox
              node-key="id"
              highlight-current
              :check-strictly="false"
              :props="customerTreeProps"
              :load="loadCustomerNode"
              lazy
              class="customer-tree"
              style="min-height: 300px; max-height: 400px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;"
              @check-change="handleCustomerTreeCheckChange"
              @node-expand="handleNodeExpand"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup name="CustomerSelect" lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { listCustomerSegment } from '@/api/customer/customer-segment'
import { listMerchant, listMerchantTree } from '@/api/merchant/merchant'
import { listCustomer } from '@/api/customer/customer'

// 定义属性
const props = defineProps({
  modelValue: {
    type: String,
    default: '{}'
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue'])

// 表单数据
const form = reactive({
  startTime: '',
  endTime: ''
})

// 客户来源选项
const merchantTreeData = ref([])

// 客户标签选项
const customerTags = ref([
  { value: 'vip', label: 'VIP客户' },
  { value: 'potential', label: '潜在客户' },
  { value: 'loyal', label: '忠实客户' }
])

// 客户分层列表
const customerSegments = ref([])

// 选中的客户来源
const selectedSources = ref([])

// 选中的客户标签
const selectedTags = ref([])

// 选中的客户分层
const selectedSegments = ref([])

// 时间范围选项
const timeRangeOption = ref('7d')

// 自定义时间范围
const customTimeRange = ref([])

// 客户树相关
const customerTreeRef = ref()
const customerTreeData = ref([])
const customerTreeProps = {
  label: 'label',
  children: 'children',
  isLeaf: 'isLeaf'
}

// 缓存待设置的选中客户
const pendingSelectedCustomers = ref([])

// 树形控件配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 处理时间范围变化
function handleTimeRangeChange(value) {
  const now = new Date()
  let startDate, endDate
  
  switch (value) {
    case '3d':
      startDate = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000)
      endDate = now
      break
    case '7d':
      startDate = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000)
      endDate = now
      break
    case '1m':
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate())
      endDate = now
      break
    case 'custom':
      // 自定义时间范围，清空开始和结束时间
      form.startTime = ''
      form.endTime = ''
      return
    default:
      return
  }
  
  // 格式化日期
  form.startTime = formatDate(startDate)
  form.endTime = formatDate(endDate)
}

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 加载客户节点
function loadCustomerNode(node, resolve) {
  const { level, data } = node;
  
  // 根节点，加载商户数据
  if (level === 0) {
    listMerchant({}).then(response => {
      const merchants = response.data.records || response.data || []
      const merchantNodes = merchants.map(merchant => ({
        id: `m_${merchant.merchantCode}`,
        label: merchant.merchantName,
        merchantCode: merchant.merchantCode,
        isLeaf: false
      }))
      resolve(merchantNodes)
    }).catch(() => {
      resolve([
        { id: 'm_1', label: '自平台', merchantCode: '1', isLeaf: false },
        { id: 'm_2', label: '千山集', merchantCode: '2', isLeaf: false }
      ])
    })
    return
  }
  
  // 加载客户数据
  if (level > 0 && data.merchantCode) {
    const params = {
      merchantCode: data.merchantCode,
      pageNumber: 1,
      pageSize: 100
    }
    
    listCustomer(params).then(response => {
      const customers = response.data.records || response.data || []
      const customerNodes = customers.map(customer => ({
        id: `u_${customer.id}`,
        label: customer.customerName,
        customerId: customer.id,
        isLeaf: true
      }))
      resolve(customerNodes)
      
      // 如果有待设置的选中客户，在数据加载完成后设置选中状态
      if (pendingSelectedCustomers.value.length > 0 && customerTreeRef.value) {
        nextTick(() => {
          setCheckedKeys(pendingSelectedCustomers.value)
          // 清空待处理的客户列表
          pendingSelectedCustomers.value = []
        })
      }
    }).catch(() => {
      resolve([])
    })
  }
}

// 处理节点展开
function handleNodeExpand(data, node, component) {
  // 节点展开时，如果有待设置的选中客户，尝试设置
  if (pendingSelectedCustomers.value.length > 0) {
    nextTick(() => {
      setCheckedKeys(pendingSelectedCustomers.value)
    })
  }
}

// 设置选中节点
function setCheckedKeys(keys) {
  if (customerTreeRef.value) {
    try {
      customerTreeRef.value.setCheckedKeys(keys)
    } catch (e) {
      console.error('设置选中节点失败:', e)
      // 如果直接设置失败，尝试逐个设置
      keys.forEach(key => {
        try {
          customerTreeRef.value.setChecked(key, true, false)
        } catch (innerError) {
          console.error('设置单个节点失败:', key, innerError)
        }
      })
    }
  }
}

// 处理客户树节点勾选变化
function handleCustomerTreeCheckChange(data, checked, indeterminate) {
  // 当check-strictly设为false时，父节点会根据子节点的选中状态自动更新
  // 这里可以添加额外的处理逻辑（如果需要）
  // 触发更新以确保选中的客户能及时传递给父组件
  const customerGroup = {
    sources: selectedSources.value,
    tags: selectedTags.value,
    segments: selectedSegments.value,
    startTime: form.startTime,
    endTime: form.endTime,
    selectedCustomers: getSelectedCustomers()
  }
  emit('update:modelValue', JSON.stringify(customerGroup))
  
  // 清空待处理的客户列表，因为我们已经更新了实际的树组件
  pendingSelectedCustomers.value = []
}

// 获取选中的客户
function getSelectedCustomers() {
  // 优先从树组件获取当前选中的节点
  if (customerTreeRef.value) {
    return customerTreeRef.value.getCheckedKeys() || [];
  }
  
  // 如果树组件未初始化，从缓存中获取
  if (pendingSelectedCustomers.value.length > 0) {
    return pendingSelectedCustomers.value;
  }
  
  // 如果都没有，则从传入的modelValue中获取
  if (typeof props.modelValue === 'string' && props.modelValue !== '{}') {
    try {
      const customerGroup = JSON.parse(props.modelValue);
      return customerGroup.selectedCustomers || [];
    } catch (e) {
      console.error('解析客户群体数据失败:', e);
    }
  }
  
  // 默认返回空数组
  return [];
}

// 刷新客户树组件，确保正确显示已选中的客户
function refreshCustomerTree() {
  // 如果有待设置的选中客户，尝试重新设置
  if (pendingSelectedCustomers.value.length > 0 && customerTreeRef.value) {
    nextTick(() => {
      setCheckedKeys(pendingSelectedCustomers.value)
    })
  } 
  // 如果没有待处理的客户，但树组件已初始化，尝试从modelValue中获取
  else if (customerTreeRef.value && props.modelValue) {
    try {
      const customerGroup = JSON.parse(props.modelValue)
      if (customerGroup.selectedCustomers && customerGroup.selectedCustomers.length > 0) {
        nextTick(() => {
          setCheckedKeys(customerGroup.selectedCustomers)
        })
      }
    } catch (e) {
      console.error('解析客户群体数据失败:', e)
    }
  }
}

// 提供一个方法供父组件调用以获取最新的选中客户
defineExpose({
  getSelectedCustomers,
  refreshCustomerTree
})

// 监听数据变化并更新父组件
watch([selectedSources, selectedTags, selectedSegments, form], () => {
  const customerGroup = {
    sources: selectedSources.value,
    tags: selectedTags.value,
    segments: selectedSegments.value,
    startTime: form.startTime,
    endTime: form.endTime,
    selectedCustomers: getSelectedCustomers()
  }
  emit('update:modelValue', JSON.stringify(customerGroup))
}, { deep: true })

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    try {
      const customerGroup = JSON.parse(newVal)
      selectedSources.value = customerGroup.sources || []
      selectedTags.value = customerGroup.tags || []
      selectedSegments.value = customerGroup.segments || []
      form.startTime = customerGroup.startTime || ''
      form.endTime = customerGroup.endTime || ''
      
      // 设置选中的客户
      if (customerGroup.selectedCustomers && customerGroup.selectedCustomers.length > 0) {
        // 将选中的客户ID缓存起来，等树组件数据加载完成后再设置
        pendingSelectedCustomers.value = customerGroup.selectedCustomers
        
        // 如果树组件已经初始化，直接设置选中状态
        if (customerTreeRef.value) {
          nextTick(() => {
            setCheckedKeys(customerGroup.selectedCustomers)
            pendingSelectedCustomers.value = []
          })
        }
      } else {
        // 清空选中状态
        pendingSelectedCustomers.value = []
        if (customerTreeRef.value) {
          nextTick(() => {
            setCheckedKeys([])
          })
        }
      }
    } catch (e) {
      console.error('解析客户群体数据失败:', e)
    }
  }
}, { immediate: true })

// 组件挂载时获取数据
onMounted(() => {
  listMerchantTree({}).then(response => {
    merchantTreeData.value = response.data || []
  }).catch(() => {
    merchantTreeData.value = [
      { id: 'm_1', label: '自平台', merchantCode: '1' },
      { id: 'm_2', label: '千山集', merchantCode: '2' }
    ]
  })
  
  getCustomerSegments()
  // 初始化时间范围
  handleTimeRangeChange(timeRangeOption.value)
  
  // 检查是否有待处理的选中客户
  if (pendingSelectedCustomers.value.length > 0 && customerTreeRef.value) {
    nextTick(() => {
      setCheckedKeys(pendingSelectedCustomers.value)
    })
  }
})

// 获取客户分层列表
function getCustomerSegments() {
  listCustomerSegment({}).then(response => {
    customerSegments.value = response.data.records || response.data || []
  }).catch(() => {
    customerSegments.value = [
      { id: 'segment_1', segmentName: '高价值客户' },
      { id: 'segment_2', segmentName: '普通客户' }
    ]
  })
}

</script>

<style scoped>
.customer-select {
  padding: 20px;
}

.form-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 0;
}

</style>